package com.wangkang.eduservice.service.impl;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.wangkang.eduservice.client.VodClient;
import com.wangkang.eduservice.entity.EduVideo;
import com.wangkang.eduservice.enums.EduResultCode;
import com.wangkang.eduservice.mapper.EduVideoMapper;
import com.wangkang.eduservice.service.EduVideoService;
import com.wangkang.servicebase.exceptionhandler.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author wangkang
 * @since 2022-04-13
 */
//用this或baseMapper来调用底层已定义好的方法，但仅能用baseMapper调用自己定义的方法。
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    private  VodClient vodClient;

    public EduVideoServiceImpl(VodClient vodClient) {
        this.vodClient = vodClient;
    }

    /**
     * 根据课程id删除视频(远程调用deleteBatch方法)
     *
     * @param courseId
     */
    @Override
    public void deleteVideoByCourseId(String courseId) {
        //LambdaQueryWrapper<EduVideo> queryWrapper = new LambdaQueryWrapper<>();
        QueryWrapper<EduVideo> queryWrapper = new QueryWrapper<>();
        //根据video表中的course_id字段，作为查询条件;
        queryWrapper.eq("course_id",courseId);
        //queryWrapper.eq(EduVideo::getCourseId,courseId);
        //又根据video表中的video_source_id字段，作为select方法的查询条件，通过selectList方法去查询出EduVideo小节对象。
        //queryWrapper.select(EduVideo::getVideoSourceId);
        queryWrapper.select("video_source_id");
        List<EduVideo> videoList = baseMapper.selectList(queryWrapper);
        //List<EduVideo> videoList = this.list(queryWrapper);

        //List<EduVideo>变成List<String>
        List<String> videoSourceIdList=new ArrayList<>();
        for (int i = 0; i < videoList.size(); i++) {
            EduVideo eduVideo=videoList.get(i);
            String videoSourceId= eduVideo.getVideoSourceId();
            if(StringUtils.isNotBlank(videoSourceId)){
            //放到videoSourceIdList集合里面
            videoSourceIdList.add(videoSourceId);
            }
        }



//        List<String> videoSourceIdList = videoList.stream()
//                .map(EduVideo::getVideoSourceId)
//                .collect(toList());

        //删除阿里云多个视频
        if(!CollectionUtils.isEmpty(videoSourceIdList)){
            //远程调用deleteBatch方法
            //根据多个视频id删除多个视频
            vodClient.deleteBatch(videoSourceIdList);
        }
        //删除小节
        boolean removeResult = this.remove(queryWrapper);
        if(!removeResult){
            throw GuliException.from(EduResultCode.DELETE_ERROR);
        }
    }
}